<template>
  <el-row style="height:100%">
    <page report="true">
      <div class="page-content report-con">
        <reportheader :isDisabledTims='isDisabledTims'
                      :tags='global.tags'>
        </reportheader>
        <div class="kpi">
          <el-checkbox-group class="kpiBox" v-model="headParams.nowKpisKey" size="small" @change="kpiTypeChange">
            <el-checkbox-button v-for="item in headParams.show_kpislist" v-if="item.type == 1"
                                :disabled="headParams.nowKpisKey.includes('stay') && (item.name == 'enters' || item.name == 'exits') ? true : false"
                                :key="item.id" :label="item.key">{{item.name}}
            </el-checkbox-button>
          </el-checkbox-group>
          <el-button class="kpiMore"  type="primary" size="small" @click="showTransfer = true">更多 <i class="el-icon-share"></i></el-button>
        </div>
        <p v-if="headParams.nowKpisKey.length == 0" class="tips">请点击查询报表获取相关数据</p>
        <template v-for="item in headParams.nowKpisKey">
          <div class="card">
            <reportSaleCharts :ref="'echart' + item" :EchartData="EchartData"></reportSaleCharts>
          </div>
          <div class="hei13"></div>
        </template>
<!--        <div class="isShowTable">-->
<!--          <el-button v-show="!isShowTable" type="primary" @click="isShowTable = true" size="samll" class="isShowTableBtn">-->
<!--            加载报表 <i class="el-icon-arrow-down"></i>-->
<!--          </el-button>-->
<!--        </div>-->
<!--        <reporttable v-if="isShowTable" :isType="'case'" :tableData="table.tableData" :tableHead="table.tableHead" :showType="showType" :comp_name="DataV.comp_name"-->
<!--                     ref='table' :title="global.title" :isShowExport = "timeSize.isShow"></reporttable>-->
      </div>
    </page>
    <el-dialog title="选择更多指标" :visible.sync="showTransfer" class="sale-charts-dialog"
               append-to-body style="text-align: center"  @closed="menuClose">
      <el-transfer
        id="transferKPI"
        style="text-align: left; display: inline-block;"
        v-model="headParams.kpisKey"
        :props="{
            key: 'key',
            label: 'name'
          }"
        filterable
        :titles="['未显示指标', '已显示指标']"
        :button-texts="['删除', '添加']"
        :format="{
            noChecked: '${total}',
            hasChecked: '${checked}/${total}'
          }"
        :data="headParams.all_kpislist">
      </el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showTransfer = false" size="small">取 消</el-button>
        <el-button type="primary" @click="confirmRoleTransfer" size="small">保 存</el-button>
      </div>
    </el-dialog>
  </el-row>
</template>
<style lang="scss">
  .page-content {
    &.report-con {
      padding: 0 0;
    }
    padding: 15px;
    .card{
      width: 100%;
      background: #fff;
      padding: 15px 10px;
      overflow: hidden;
    }

    .fr {
      float: right;
    }

    .el-table {
      margin-bottom: 10px;
    }

    .paging {
      margin: 15px;
      height: 28px;
    }

    .hei13 {
      height: 15px;
      width: 100%;
    }
    .kpi{
      text-align: right;
      margin: 20px 60px;
      .kpiBox{
        display: inline-block;
        vertical-align: top;
      }
      .kpiMore{
        display: inline-block;
        vertical-align: top;
      }
    }
    .tips{
      display: inline-block;
      width: 100%;
      text-align: center;
      font-size: 20px;
      color:#ccc;

    }
  }
</style>
<script>
  let moment = require("moment");
  import page from "@/components/page/page";
  import reportheader from "@/components/analyzeReport/reportpublic/reportInformationHead";
  import reportSaleCharts from "@/components/analyzeReport/reportpublic/reportInformationEcharts";
  import reporttable from "@/components/analyzeReport/reportpublic/reporttable";
  import reportGlobal from "@/components/global/reportGlobal";//公共配置
  let unit = reportGlobal.unit;
  let kpiColor = reportGlobal.colorList;
  let kpiName = reportGlobal.name;
  let showTableMaxItemList = reportGlobal.showTableMaxItemList;

  export default {
    data() {
      return {
        headParams:{
          org_id_list:'',
          org_type:'',
          start_day:'',
          end_day:'',
          start_hm:'',
          end_hm:'',
          all_kpislist:[],//全部的指标数组
          show_kpislist:[],//显示的指标数组
          kpisKey:[],//当前显示的指标（key值）
          nowKpisKey:[],//当前选中的指标
        },//请求接口参数
        KPIList:[],//kpi数组
        commonData:[],
        showTransfer:false,//是否显示穿梭框
        saveKPi:{},//保存的kpi参数
        record:'',          //记录指标点击为最后一个值
        recordKPIList:[],//临时保存穿梭框状态

        EchartData:null,//echart数据
        EchartTitle:{
          enters:''
        },//echartTitle

        isDisabledTims:false,
        code: this.$route.query.code,        //通过菜单栏点击传过来的code判断使用的公共参数
        global:{}//设置的页面参数
      }
    },
    inject:['reload'],
    components: {
      page,
      reportheader,
      reportSaleCharts,
      reporttable,
    },
    created() {
      for (let i in reportGlobal.queryList) {
        if (this.code == reportGlobal.queryList[i].code) {
          this.global = reportGlobal.queryList[i]
        }
      }
    },
    mounted() {
      this.$Bus.$on('UpCondition',(data,dataIsChange)=>{
        // console.log(data);
        this.headParams.org_id_list = data.case_id_list;
        this.headParams.org_type = 2;
        this.headParams.start_day = data.start_day;
        this.headParams.end_day = data.end_day;
        this.headParams.start_hm = data.start_hm;
        this.headParams.end_hm = data.end_hm;
        //判断点击按钮是查询报表还是刷新数据
        if(dataIsChange){
          this.getKPI()
        }else{
          this.updata()
        }

      })
    },
    beforeDestroy() {
      this.$Bus.$off('UpCondition')
    },
    watch: {
      commonData:{
        handler(val){
          if(val && Object.keys(val).length) {
            this.upEcharts();
            this.upTable();
          }
        },
        deep:true
      },
      //当route变化的时候，主要是报表之前传参
      $route(){
        this.reload()
      },
    },
    methods:{
      //获取kpi
      getKPI() {
        this.$Bus.$emit('Loading', true);
        let getKPIList = ()=>{
          let p = new Promise((res,rej)=>{
            let url='/sys/report_assist_new/get_indicator_list'
            let params = {
              org_id_list : this.headParams.org_id_list,
              org_type : this.headParams.org_type
            }
            this.$api.post(url,params)
            .then(data => {
              if(data == '10001'){
                this.$message.error('无权操作该数据')
                rej()
              }
              if (data) {
                res(data.data)
              } else {
                rej()
              }
            })
            .catch(err => {
              rej(err)
              console.log(err, '企业下无指标');
              this.removedata();
              this.$Bus.$emit('Loading', false);
            })
          })
          return p
        }
        //获取当前显示的kpi
        let getShowKPI = ()=>{
          let p = new Promise((res,rej)=>{
            let url = '/sys/report_assist_new/set_web_custom_storage?w_key='+ this.code
            this.$api.get(url)
            .then(data=>{
              res(data.data)
            })
            .catch(err=>{
              rej(err)
            })
          })
          return p
        }
        Promise.all([getKPIList(),getShowKPI()])
        .then(data=>{
          let kpiList = data[0]
          let showKPi = data[1]
          // console.log(kpiList);
          // console.log(showKPi);
          this.headParams.all_kpislist = kpiList.filter(x => {
            return this.global.indicator_keys.includes(x.key)
          })

          //根据id对指标进行排序
          this.headParams.all_kpislist.sort((x,y)=>{
            if(x.id < y.id){
              return -1
            }else{
              return 1
            }
          });
          //判断是否get到显示的指标
          if(showKPi){
            showKPi = JSON.parse(showKPi)
            this.headParams.show_kpislist = [];
            for(let i in showKPi){
              for(let j in this.headParams.all_kpislist){
                if(this.headParams.all_kpislist[j].key == i && showKPi[i]){
                  this.headParams.show_kpislist.push(this.headParams.all_kpislist[j])
                }
              }
            }
          }else{
            this.headParams.show_kpislist = this.headParams.all_kpislist.filter(x => {
              return this.global.showKPI.includes(x.key)
            })
          }
          //判断显示的kpi值有没有
          if(this.headParams.show_kpislist.length == 0){
            this.headParams.show_kpislist = this.headParams.all_kpislist.length <= 8 ? this.headParams.all_kpislist.map(x=>x) :
              this.headParams.all_kpislist.filter((x,i)=>{
                return i <= 7
              })
          }
          this.headParams.kpisKey = this.headParams.show_kpislist.map(x=>x.key)
          this.headParams.nowKpisKey = Array.of(this.headParams.show_kpislist[0].key)
          this.record = this.headParams.show_kpislist[0].key
          this.recordKPIList = this.headParams.kpisKey

           console.log(this.headParams,'headParams');
          this.updata()
          this.$Bus.$emit('Loading', false);
        })
        .catch(err=>{
          console.log(err);
        })
      },
      //指标选择change事件
      kpiTypeChange(val){
        if (val.length < 1) {
          this.headParams.nowKpisKey.push(this.record);
        } else if (val.length == 1) {
          this.record = val[0];
        }
        this.$nextTick(()=>{
          this.changeEchartData()
        })
      },
      //
      menuClose(){
        this.headParams.kpisKey = this.recordKPIList
      },
      //保存
      confirmRoleTransfer(){
        //先判断选中的指标个数，不能为空
        if(this.headParams.kpisKey.length > 8){
          this.$message.warning('指标选择最多不得超过8个！')
        }else if(this.headParams.kpisKey.length){
          this.headParams.show_kpislist = this.headParams.all_kpislist.filter(x=>{
            return this.headParams.kpisKey.includes(x.key)
          })
          this.headParams.nowKpisKey = Array.of(this.headParams.show_kpislist[0].key)
          this.$Bus.$emit('Loading', true);
          this.saveKPI()
        }else{
          this.$message.warning('请至少选择一个指标')
        }
      },
      saveKPI(){
        let showKPIList = this.headParams.show_kpislist.map(x=>x.key)

        for(let i in this.headParams.all_kpislist){
          this.saveKPi[this.headParams.all_kpislist[i].key] = showKPIList.includes(this.headParams.all_kpislist[i].key) ? true : false
        }
        let url = '/sys/report_assist_new/set_web_custom_storage'
        let params = {
          w_key: this.code,
          w_value: JSON.stringify(this.saveKPi)
        }
        this.$api.post(url,params)
        .then(data=>{
          if(data){
            this.recordKPIList = showKPIList
            this.showTransfer = false
            this.updata()
          }
          this.$Bus.$emit('Loading', false);
        })
        .catch(err=>{
          this.$message.error('保存指标失败，请重试！')
          this.$Bus.$emit('Loading', false);
        })
      },

      updata(){
        this.$Bus.$emit("Loading", true);
        let url = '/sys/report_new/distribution_sum?sort_type=desc&sort_key=' + this.headParams.kpisKey[0] +
          '&tags=' + this.global.tags + '&indicator_keys=' + this.headParams.kpisKey + '&group_type=' + this.global.group_type +
        '&start_day=' + this.headParams.start_day + '&end_day=' + this.headParams.end_day + '&start_hm=' + this.headParams.start_hm + '&end_hm=' + this.headParams.end_hm;
        let params = {
          org_id_list:this.headParams.org_id_list,
          org_type:this.headParams.org_type
        }
        this.$api.post(url,params)
        .then(data => {
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit("Loading", false);
            return
          }

          if (data && data.data) {
            let item_list_length = data.data.item_list ? data.data.item_list.length : 0//获取item_list的长度
            //判断是否直接显示报表，如果item_list_length > 20 时，则不显示报表
            this.isShowTable = item_list_length > showTableMaxItemList ? false : true

            if (data.data.item_list && data.data.item_list.length > 0){
              this.commonData = data.data;     //改变数据
              // console.log(this.commonData);
            } else {
              console.log("区域下无数据");
              this.removedata();
            }
          } else {
            this.$message.error('没有数据！')
            this.removedata();
          }
          this.$Bus.$emit("Loading", false);
        })
        .catch(err => {
           console.log(err);
          this.removedata();
          this.$Bus.$emit("Loading", false);
        });
      },
      removedata(){
        this.commonData = null;
        this.EchartData = null
        let nowKpisKey_arr = this.headParams.nowKpisKey;//当前选中的指标数组
        for (let i in nowKpisKey_arr) {
          let title = kpiName[nowKpisKey_arr[i]] + '-业态分析数据'
          this.$refs['echart' + nowKpisKey_arr[i]][0].upData(false,'',title)
        }
      },
      //配置echarts参数
      upEcharts(){
        // console.log(this.commonData);
        let item_list = JSON.parse(JSON.stringify(this.commonData.item_list))
        item_list.sort((x,y)=>{return x.tag_id - y.tag_id})
        let sum_list = this.commonData.sum_list
        let kpisKey_arr = this.headParams.kpisKey;//当前所显示的指标数组
        let nowKpisKey_arr = this.headParams.nowKpisKey;//当前选中的指标数组

        let EchartData = {
          tag_name_arr:[],
          tag_id_arr:[],
          value:[]
        }
        for(let i in item_list){
          let obj = {}
          EchartData.tag_name_arr.push(item_list[i].tag_name)
          EchartData.tag_id_arr.push(item_list[i].tag_id)
          for(let j in kpisKey_arr){
            let key = kpisKey_arr[j]
            obj[key] = Number(item_list[i][key])
          }
          EchartData.value.push(obj)
        }
        this.EchartData = EchartData
        this.changeEchartData()
      },

      //加载Echart组件
      changeEchartData(){
        if(this.EchartData){
          let nowKpisKey_arr = this.headParams.nowKpisKey;//当前选中的指标数组
          for (let i in nowKpisKey_arr) {
            let title = kpiName[nowKpisKey_arr[i]] + '-业态分析数据'
            this.$refs['echart' + nowKpisKey_arr[i]][0].upData(this.EchartData, nowKpisKey_arr[i], title)
          }
        }else{
          this.removedata()
        }
      },
      //配置表格参数
      upTable(){

      },
    }
  }
</script>